<script setup lang="ts">
import { ref, reactive, onMounted, h, nextTick } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { TableColumn, PaginationConfig } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import {
  ElMessage,
  ElMessageBox,
  ElTag,
  ElButton,
  ElDialog,
  ElDescriptions,
  ElDescriptionsItem,
  ElAlert,
} from "element-plus";
import { Refresh, Plus, Connection, Delete } from "@element-plus/icons-vue";
import {
  getMaliciousAddressList,
  addMaliciousAddress,
  deleteMaliciousAddress,
  testCeyeConnection,
  getTemplateStatistics,
} from "../servers";

const loading = ref(false);
const addressList = ref<any[]>([]);
const searchFormRef = ref<DynamicFormInstance>();
const tableRef = ref();
const selectedRows = ref<any[]>([]);

// 统计信息
const statistics = ref({
  total_addresses: 0,
  active_threats: 0,
  today_verifications: 0,
  ceye_connected: false,
});

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const searchForm = reactive({
  threat_type: "",
  is_active: undefined,
  keyword: "",
});

const searchConfig: FormItemConfig[] = [
  {
    key: "threat_type",
    name: "威胁类型",
    type: "select",
    labelWidth: "80px",
    placeholder: "选择威胁类型",
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部", value: "" },
        { label: "C&C服务器", value: "c2_server" },
        { label: "僵尸网络", value: "botnet" },
        { label: "恶意软件", value: "malware" },
        { label: "钓鱼网站", value: "phishing" },
        { label: "挖矿木马", value: "mining" },
      ],
    },
  },
  {
    key: "is_active",
    name: "状态",
    type: "select",
    labelWidth: "80px",
    placeholder: "选择状态",
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部", value: undefined },
        { label: "活跃", value: true },
        { label: "非活跃", value: false },
      ],
    },
  },
  {
    key: "keyword",
    name: "搜索",
    type: "input",
    labelWidth: "80px",
    placeholder: "搜索地址或描述",
  },
];

const columns = ref<TableColumn[]>([
  {
    label: "恶意地址",
    prop: "address",
    minWidth: 200,
    show: true,
  },
  {
    label: "地址类型",
    prop: "address_type",
    width: 100,
    show: true,
    render: (row) => {
      const typeMap: Record<string, any> = {
        domain: { text: "域名", type: "info" },
        ip: { text: "IP", type: "warning" },
        url: { text: "URL", type: "danger" },
      };
      const typeInfo = typeMap[row.address_type] || {
        text: row.address_type,
        type: "info",
      };
      return h(ElTag, { type: typeInfo.type, size: "small" }, typeInfo.text);
    },
  },
  {
    label: "威胁类型",
    prop: "threat_type",
    width: 120,
    show: true,
    render: (row) => {
      const threatMap: Record<string, any> = {
        c2_server: { text: "C&C服务器", type: "danger" },
        botnet: { text: "僵尸网络", type: "warning" },
        malware: { text: "恶意软件", type: "danger" },
        phishing: { text: "钓鱼网站", type: "warning" },
        mining: { text: "挖矿木马", type: "info" },
      };
      const threatInfo = threatMap[row.threat_type] || {
        text: row.threat_type,
        type: "info",
      };
      return h(
        ElTag,
        { type: threatInfo.type, size: "small" },
        threatInfo.text
      );
    },
  },
  {
    label: "威胁家族",
    prop: "threat_family",
    width: 120,
    show: true,
  },
  {
    label: "置信度",
    prop: "confidence",
    width: 100,
    show: true,
    render: (row) => {
      const confidence = row.confidence || 0;
      const color =
        confidence >= 90
          ? "danger"
          : confidence >= 70
          ? "warning"
          : confidence >= 50
          ? "info"
          : "success";
      return h(ElTag, { type: color, size: "small" }, `${confidence}%`);
    },
  },
  {
    label: "状态",
    prop: "is_active",
    width: 100,
    show: true,
    render: (row) => {
      const statusMap: Record<string, any> = {
        true: { text: "活跃", type: "danger" },
        false: { text: "非活跃", type: "success" },
      };
      const statusInfo = statusMap[row.is_active] || {
        text: "未知",
        type: "info",
      };
      return h(
        ElTag,
        { type: statusInfo.type, size: "small" },
        statusInfo.text
      );
    },
  },
  {
    label: "最后验证",
    prop: "last_verified",
    width: 150,
    show: true,
  },
  {
    label: "标签",
    prop: "tags",
    width: 150,
    show: true,
    render: (row) => {
      if (!row.tags || !Array.isArray(row.tags)) return h("span", {}, "无");
      return h(
        "div",
        {},
        row.tags.map((tag: string) =>
          h(
            ElTag,
            { size: "small", type: "info", style: "margin-right: 4px" },
            tag
          )
        )
      );
    },
  },
  {
    label: "操作",
    prop: "action",
    width: 180,
    fixed: "right",
    show: true,
    slot: "action",
  },
]);

const showDetailDialog = ref(false);
const showAddDialog = ref(false);
const showCeyeTestDialog = ref(false);
const showCeyeResultDialog = ref(false);
const addressDetail = ref<any>(null);
const ceyeTestResult = ref<any>(null);
const loadingDetail = ref(false);
const formRef = ref<DynamicFormInstance>();

const formData = reactive({
  address: "",
  address_type: "domain",
  threat_type: "",
  threat_family: "",
  confidence: 50,
  tags: "" as string | string[],
  description: "",
});

const ceyeTestData = reactive({
  config_name: "default",
});

const addFormConfig: FormItemConfig[] = [
  {
    key: "address",
    name: "恶意地址",
    type: "input",
    labelWidth: "100px",
    placeholder: "请输入恶意地址",
    rules: [{ required: true, message: "请输入恶意地址" }],
  },
  {
    key: "address_type",
    name: "地址类型",
    type: "select",
    labelWidth: "100px",
    placeholder: "选择地址类型",
    rules: [{ required: true, message: "请选择地址类型" }],
    params: {
      options: [
        { label: "域名", value: "domain" },
        { label: "IP地址", value: "ip" },
        { label: "URL", value: "url" },
      ],
    },
  },
  {
    key: "threat_type",
    name: "威胁类型",
    type: "select",
    labelWidth: "100px",
    placeholder: "选择威胁类型",
    params: {
      clearable: true,
      options: [
        { label: "C&C服务器", value: "c2_server" },
        { label: "僵尸网络", value: "botnet" },
        { label: "恶意软件", value: "malware" },
        { label: "钓鱼网站", value: "phishing" },
        { label: "挖矿木马", value: "mining" },
      ],
    },
  },
  {
    key: "threat_family",
    name: "威胁家族",
    type: "input",
    labelWidth: "100px",
    placeholder: "请输入威胁家族",
  },
  {
    key: "confidence",
    name: "置信度",
    type: "slider",
    labelWidth: "100px",
    params: {
      min: 0,
      max: 100,
      showInput: true,
    },
  },
  {
    key: "tags",
    name: "标签",
    type: "input",
    labelWidth: "100px",
    placeholder: "请输入标签，多个用逗号分隔",
  },
  {
    key: "description",
    name: "描述",
    type: "textarea",
    labelWidth: "100px",
    placeholder: "请输入描述",
    params: {
      rows: 3,
    },
  },
];

const fetchAddressList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      ...searchForm,
    };
    // 移除空值
    Object.keys(params).forEach((key) => {
      if (
        params[key] === "" ||
        params[key] === null ||
        params[key] === undefined
      ) {
        delete params[key];
      }
    });
    const { data } = await getMaliciousAddressList(params);

    addressList.value = data?.items || [];
    pagination.total = data?.total || 0;
  } catch (error) {
    ElMessage.error("获取恶意地址列表失败");
  } finally {
    loading.value = false;
  }
};

const fetchStatistics = async () => {
  try {
    // 测试代外连接状态
    const ceyeResult = await testCeyeConnection();
    statistics.value.ceye_connected = ceyeResult.data?.connected || false;

    // 调用模板统计接口获取统计信息
    const statsResult = await getTemplateStatistics();
    if (statsResult.data) {
      const data = statsResult.data;
      statistics.value = {
        total_addresses: data.total_templates || 0,
        active_threats:
          data.category_stats?.reduce(
            (sum: number, item: any) => sum + item.count,
            0
          ) || 0,
        today_verifications:
          data.template_stats?.reduce(
            (sum: number, item: any) => sum + item.usage_count,
            0
          ) || 0,
        ceye_connected: statistics.value.ceye_connected,
      };
    } else {
      // 如果统计接口失败，使用列表数据计算（确保addressList是数组）
      if (Array.isArray(addressList.value)) {
        statistics.value = {
          total_addresses: addressList.value.length,
          active_threats: addressList.value.filter((a) => a.is_active).length,
          today_verifications: 0,
          ceye_connected: statistics.value.ceye_connected,
        };
      } else {
        // 如果addressList不是数组，设置默认值
        statistics.value = {
          total_addresses: 0,
          active_threats: 0,
          today_verifications: 0,
          ceye_connected: statistics.value.ceye_connected,
        };
      }
    }
  } catch (error) {
    console.error("获取统计信息失败:", error);
    // 出错时使用列表数据计算
    if (Array.isArray(addressList.value)) {
      statistics.value = {
        total_addresses: addressList.value.length,
        active_threats: addressList.value.filter((a) => a.is_active).length,
        today_verifications: 0,
        ceye_connected: statistics.value.ceye_connected,
      };
    }
  }
};

const handleSearch = (value: any) => {
  Object.assign(searchForm, value);
  pagination.currentPage = 1;
  fetchAddressList();
  fetchStatistics(); // 搜索时也更新统计信息
};

const handleSearchReset = () => {
  searchFormRef.value?.resetFields();
  Object.assign(searchForm, {
    threat_type: "",
    is_active: undefined,
    keyword: "",
  });
  pagination.currentPage = 1;
  fetchAddressList();
  fetchStatistics(); // 重置时也更新统计信息
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchAddressList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchAddressList();
};

const handleViewDetail = async (row: any) => {
  addressDetail.value = row;
  showDetailDialog.value = true;
};

const handleAdd = () => {
  Object.assign(formData, {
    address: "",
    address_type: "domain",
    threat_type: "",
    threat_family: "",
    confidence: 50,
    tags: "",
    description: "",
  });
  showAddDialog.value = true;
  nextTick(() => {
    formRef.value?.resetFields();
  });
};

const handleCloseAddDialog = () => {
  showAddDialog.value = false;
  formRef.value?.resetFields();
  Object.assign(formData, {
    address: "",
    address_type: "domain",
    threat_type: "",
    threat_family: "",
    confidence: 50,
    tags: "",
    description: "",
  });
};

const handleSubmitForm = async (values: any) => {
  try {
    const submitData = values;
    await addMaliciousAddress(submitData);
    ElMessage.success("恶意地址添加成功");
    showAddDialog.value = false;
    fetchAddressList();
    fetchStatistics();
  } catch (error) {
    ElMessage.error("添加失败");
  }
};

const handleTestCeye = () => {
  showCeyeTestDialog.value = true;
};

const handleSubmitCeyeTest = async () => {
  try {
    const { data } = await testCeyeConnection(ceyeTestData);
    ceyeTestResult.value = data;
    statistics.value.ceye_connected = data?.success || false;
    showCeyeTestDialog.value = false;
    showCeyeResultDialog.value = true;
  } catch (error) {
    ElMessage.error("Ceye连接测试失败");
    statistics.value.ceye_connected = false;
  }
};

const handleCloseCeyeTestDialog = () => {
  showCeyeTestDialog.value = false;
  formRef.value?.resetFields();
  Object.assign(ceyeTestData, {
    config_name: "default",
  });
};

const handleCloseCeyeResultDialog = () => {
  showCeyeResultDialog.value = false;
  ceyeTestResult.value = null;
};

const handleDeleteAddress = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除恶意地址 "${row.address}" 吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    await deleteMaliciousAddress({
      ids: [row.id || row.address_id] as any,
    });
    ElMessage.success("删除成功");
    fetchAddressList();
    fetchStatistics();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要删除的地址");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个恶意地址吗？`,
      "批量删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const ids = selectedRows.value.map((row) => row.id || row.address_id);
    await deleteMaliciousAddress({ ids });
    ElMessage.success(`成功删除 ${selectedRows.value.length} 个恶意地址`);

    // 清空选择
    tableRef.value?.clearSelection();
    selectedRows.value = [];

    // 刷新数据
    fetchAddressList();
    fetchStatistics();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量删除失败");
    }
  }
};

// 暴露方法给父组件
defineExpose({
  fetchAddressList,
  fetchStatistics,
  statistics,
});

onMounted(() => {
  fetchAddressList();
  fetchStatistics();
});
</script>

<template>
  <div>
    <el-card shadow="never">
      <div class="search-form-container">
        <DynamicForm
          ref="searchFormRef"
          v-model="searchForm"
          :form-config="searchConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleSearchReset"
        />
      </div>
    </el-card>

    <div style="height: 10px"></div>

    <el-card>
      <el-descriptions title="验证统计" :column="4" border>
        <el-descriptions-item label="总地址数">
          <el-tag type="info" size="large">{{
            statistics.total_addresses
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="活跃威胁">
          <el-tag type="danger" size="large">{{
            statistics.active_threats
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="今日验证">
          <el-tag type="warning" size="large">{{
            statistics.today_verifications
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="Ceye连接">
          <el-tag
            :type="statistics.ceye_connected ? 'success' : 'danger'"
            size="large"
          >
            {{ statistics.ceye_connected ? "已连接" : "未连接" }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <div style="height: 10px"></div>

    <el-card>
      <DynamicTable
        ref="tableRef"
        :columns="columns"
        :data="addressList"
        :loading="loading"
        :pagination="pagination"
        selection-type="multiple"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
      >
        <template #toolbar-left>
          <el-button type="primary" @click="handleAdd"> 新增地址 </el-button>
          <el-button
            type="danger"
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            批量删除 ({{ selectedRows.length }})
          </el-button>
          <el-button type="warning" @click="handleTestCeye">
            测试代外连接
          </el-button>
          <!-- <el-button type="primary" :icon="Refresh" @click="fetchAddressList">
            刷新
          </el-button> -->
        </template>

        <template #action="{ row }">
          <el-button type="primary" size="small" @click="handleViewDetail(row)">
            详情
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDeleteAddress(row)"
          >
            删除
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 地址详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="地址详情" width="800px">
      <el-descriptions
        v-if="addressDetail"
        :column="2"
        border
        v-loading="loadingDetail"
      >
        <el-descriptions-item label="恶意地址">{{
          addressDetail.address
        }}</el-descriptions-item>
        <el-descriptions-item label="地址类型">
          <el-tag
            :type="
              addressDetail.address_type === 'domain'
                ? 'info'
                : addressDetail.address_type === 'ip'
                ? 'warning'
                : 'danger'
            "
          >
            {{
              addressDetail.address_type === "domain"
                ? "域名"
                : addressDetail.address_type === "ip"
                ? "IP"
                : "URL"
            }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="威胁类型">{{
          addressDetail.threat_type
        }}</el-descriptions-item>
        <el-descriptions-item label="威胁家族">{{
          addressDetail.threat_family || "无"
        }}</el-descriptions-item>
        <el-descriptions-item label="置信度">
          <el-tag
            :type="
              addressDetail.confidence >= 90
                ? 'danger'
                : addressDetail.confidence >= 70
                ? 'warning'
                : addressDetail.confidence >= 50
                ? 'info'
                : 'success'
            "
          >
            {{ addressDetail.confidence }}%
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="addressDetail.is_active ? 'danger' : 'success'">
            {{ addressDetail.is_active ? "活跃" : "非活跃" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="最后验证">{{
          addressDetail.last_verified || "无"
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          addressDetail.created_at
        }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">
          {{ addressDetail.description || "无" }}
        </el-descriptions-item>
        <el-descriptions-item label="标签" :span="2">
          <el-tag
            v-for="tag in addressDetail.tags"
            :key="tag"
            size="small"
            type="info"
            style="margin-right: 4px"
          >
            {{ tag }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 添加地址对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="新增恶意地址"
      width="600px"
      @close="handleCloseAddDialog"
    >
      <DynamicForm
        ref="formRef"
        v-model="formData"
        :form-config="addFormConfig"
        :gutter="16"
        type="submit"
        @submit="handleSubmitForm"
        @cancel="handleCloseAddDialog"
      />
    </el-dialog>

    <!-- Ceye连接测试对话框 -->
    <el-dialog
      v-model="showCeyeTestDialog"
      title="Ceye连接测试"
      width="500px"
      @close="handleCloseCeyeTestDialog"
    >
      <el-alert
        title="DNSLog平台连接测试"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      />
      <DynamicForm
        ref="formRef"
        v-model="ceyeTestData"
        :form-config="[
          {
            key: 'config_name',
            name: '配置名称',
            type: 'input',
            labelWidth: '100px',
            placeholder: '请输入配置名称',
            params: {
              defaultValue: 'default',
            },
          },
        ]"
        :gutter="16"
        type="submit"
        @submit="handleSubmitCeyeTest"
        @cancel="handleCloseCeyeTestDialog"
      />
    </el-dialog>

    <!-- Ceye测试结果对话框 -->
    <el-dialog
      v-model="showCeyeResultDialog"
      title="Ceye连接测试结果"
      width="600px"
      @close="handleCloseCeyeResultDialog"
    >
      <div v-if="ceyeTestResult">
        <el-descriptions title="测试结果" :column="2" border>
          <el-descriptions-item label="连接状态">
            <el-tag :type="ceyeTestResult.success ? 'success' : 'danger'">
              {{ ceyeTestResult.success ? "连接成功" : "连接失败" }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="域名">
            {{ ceyeTestResult.domain || "未知" }}
          </el-descriptions-item>
          <el-descriptions-item label="记录数量">
            <el-tag type="info">{{ ceyeTestResult.record_count || 0 }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="响应时间">
            {{
              ceyeTestResult.response_time
                ? `${ceyeTestResult.response_time}ms`
                : "未知"
            }}
          </el-descriptions-item>
          <el-descriptions-item label="消息" :span="2">
            {{ ceyeTestResult.message || "无" }}
          </el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 20px">
          <el-alert
            :title="
              ceyeTestResult.success ? 'Ceye API连接正常' : 'Ceye API连接异常'
            "
            :type="ceyeTestResult.success ? 'success' : 'error'"
            :closable="false"
            show-icon
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.search-form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
</style>
